package com.wang.scacodetest.websocker;


import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import cn.hutool.core.lang.intern.InternUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
    private Session session;
    //静态的是共有的，不限于一个类
    private static CopyOnWriteArraySet<WebSocketServer> webSocketServers=new CopyOnWriteArraySet<>();
    private static Integer count=0;
    //自定义的对应唯一的id
    private String sid;



    @OnOpen
    public void OnOpen(Session session,@PathParam("sid") String sid){
        this.session=session;
        this.sid=sid;
        addWebSocket();
        webSocketServers.add(this);
        System.out.println("当前人数为："+countWebSocket());
    }

    @OnClose
    public void OnClose(){
        webSocketServers.remove(this);
        subWebSocket();
        System.out.println("当前人数为："+countWebSocket());
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        System.out.println(throwable.getMessage());
    }

    @OnMessage
    public void onMessage(Session session,String messsage){
        for(WebSocketServer webSocketServer:webSocketServers) {
            webSocketServer.sendMessaage(messsage);
        }
    }

    public void sendMessaage(String message){
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessageBySid(String sid,String message){
        for(WebSocketServer webSocketServer:webSocketServers){
            if(ObjectUtil.isNull(sid)){
                webSocketServer.sendMessaage(message);
            }
            else {
                if(webSocketServer.sid.equals(sid)){
                    webSocketServer.sendMessaage(message);
                }
            }
        }
    }



    private static void addWebSocket(){
        count++;
    }

    private static Integer countWebSocket(){
        return count;
    }

    private static void subWebSocket(){
        count--;
    }
}